//
//  YZYH5SocialView.h
//  YZYSDKManagerDemo
//
//  Created by 赵隆杰 on 2024/6/7.
//

#import "YZYH5SocialView.h"
#import <WebKit/WebKit.h>
#import "YZYSaccountStore.h"
#import "ZCFunDataFormat.h"
#import "ZCNetworkManager.h"
#import "YZYRoleInfo.h"
#import "YZYSDKManagerHeader.h"
#import "Masonry.h"

@interface YZYH5SocialView ()<WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler>

@property (nonatomic, strong) UIButton *coverView;
@property (strong, nonatomic) WKWebView *wkWebView;

@property (nonatomic, strong) YZYRoleInfo *roleInfo;

@property (nonatomic, strong) NSDictionary *receiveMsg;

@end

@implementation YZYH5SocialView

#pragma mark - 懒加载
- (WKWebView *)wkWebView {
    if (!_wkWebView) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        config.preferences.javaScriptEnabled = YES;
        config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        config.allowsInlineMediaPlayback = YES;
        config.userContentController = [[WKUserContentController alloc] init];
//        [config setValue:@YES forKey:@"_allowUniversalAccessFromFileURLs"];
        [config.userContentController addScriptMessageHandler:self name:@"eventComplete"];
            
        _wkWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];

        if(@available(iOS 11.0, *)) {
            _wkWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        if (@available(iOS 13.0, *)) {
            _wkWebView.configuration.defaultWebpagePreferences.preferredContentMode = WKContentModeMobile;
        }
        
        _wkWebView.translatesAutoresizingMaskIntoConstraints = NO;
        _wkWebView.allowsBackForwardNavigationGestures = YES;
        _wkWebView.opaque = NO;
        _wkWebView.scrollView.backgroundColor = [UIColor clearColor];
        _wkWebView.backgroundColor = [UIColor clearColor];
        _wkWebView.UIDelegate = self;
        _wkWebView.navigationDelegate = self;
        
    }
    return _wkWebView;
}

- (instancetype)initWithRoleInfo:(YZYRoleInfo *)roleInfo receiveMsg:(NSDictionary *)receiveMsg {
    if (self == [super init]) {
        self.roleInfo = roleInfo;
        self.receiveMsg = receiveMsg;
        NSDictionary *data = (NSDictionary *)receiveMsg[@"data"];
        NSString *url = [NSString stringWithFormat:@"%@",data[@"url"]];
//        url = @"http://192.168.28.58:8082/v2/super-popup";
        self.service_url = url;
        NSLog(@"yzysdk - H5SocialView - url - %@", self.service_url);
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(applicationWillEnterForeground)
                                                     name:UIApplicationWillEnterForegroundNotification
                                                   object:nil];
    }
    return self;
}

- (void)applicationWillEnterForeground {
    NSLog(@"applicationWillEnterForeground");
    [self loadUrl];
}

- (void)loadUrl {
    if (_wkWebView == nil) return;
    [[YZYSaccountStore sharedInstance] showHUDAddedToWindow];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.service_url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20];
    [self.wkWebView loadRequest:request];
}

- (void)setService_url:(NSString *)service_url {
    _service_url = service_url;
    [self loadUrl];
}

#pragma mark - WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
//    NSLog(@"didStartProvisionalNavigation");
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
//    NSLog(@"didCommitNavigation");
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSString *injectionJSString = @"var script = document.createElement('meta');"
        "script.name = 'viewport';"
        "script.content=\"width=device-width, user-scalable=no\";"
        "document.getElementsByTagName('head')[0].appendChild(script);";
    [webView evaluateJavaScript:injectionJSString completionHandler:nil];
    [[YZYSaccountStore sharedInstance] hideHUDForWindow];
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
//    NSLog(@"didFailProvisionalNavigation");
    [self loadUrl];
    [[YZYSaccountStore sharedInstance] hideHUDForWindow];
}
// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
//    NSLog(@"didReceiveServerRedirectForProvisionalNavigation");
}
// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
//    NSLog(@"decidePolicyForNavigationResponse");
//    NSLog(@"%@",navigationResponse.response.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}
// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSLog(@"decidePolicyForNavigationAction");
    NSURLRequest *request = navigationAction.request;
    NSString *absoluteString = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];
    NSLog(@"%@",navigationAction.request.URL.absoluteString);
    
    //允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
}
 
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message {
    
    NSLog(@"yzysdk - H5SocialView - eventComplete  function=%@   params=%@", message.name, message.body);
    if([message.name isEqualToString:@"eventComplete"]) {
        NSString *bodyDataStr = [NSString stringWithFormat:@"%@",message.body];
        
        NSDictionary *params = [ZCFunDataFormat dictionaryWithJsonString:bodyDataStr];
        NSString *action = [NSString stringWithFormat:@"%@",[params objectForKey:@"action"]];

        if ([action isEqualToString:@"openPopup"]) {
            
            NSMutableDictionary *userinfo_params = [NSMutableDictionary dictionary];
            userinfo_params[@"action"] = @"openPopup";
            userinfo_params[@"data"] = [self convertDictionary:self.receiveMsg];
            [self callJS:userinfo_params];
        }
        if ([action isEqualToString:@"webDidLoad"]) {
                        
            NSMutableDictionary *userinfo_params = [NSMutableDictionary dictionary];
            userinfo_params[@"gameId"] = [ZCFunDataFormat GetQPGameID];
            userinfo_params[@"action"] = @"getSuperUserInfo";
            userinfo_params[@"data"] = [self getCryptStr];
            [self callJS:userinfo_params];
        }
        if ([action isEqualToString:@"game_switch_logout"]) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.coverView removeFromSuperview];
                [self.wkWebView removeFromSuperview];
                
                if (self.delegate && [self.delegate respondsToSelector:@selector(H5SocialView_switch_logout)]) {
                    [self.delegate H5SocialView_switch_logout];
                };
            });
            
        }
        if ([action isEqualToString:@"back_action"]) {
            [self closeH5];
        }
        if ([action isEqualToString:@"go_to_index_action"]) {
            NSString *index = [NSString stringWithFormat:@"%@",[params objectForKey:@"index"]];
            if (![index isEqualToString:@"25"]) {
                [self closeH5];
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:@"QPYZYH5SOCIALCALLBACKNotification" object:nil userInfo:params];
        }
    }
}
/*
 {"gameId":"2969","platformId":"40048","serviceId":"1","serviceName":"寒江雪","userId":"15659","roleIdPublish":"334483","roleId":"73915004","roleName":"冷承基","channeNo":"qpmailiang","goodid":"11097278","goodName":"￥600元礼包","game_order_sn":"278164010","pay_money":"6.0","orderid":"73915004","remarks":"11097278","sdkVersion":"1.2.3","deviceName":"dm1q","osType":"1","systemVersion":"REL","token":"3b9616b6bc1b49fb90e7fbfaba183065"}
 */
- (NSString *)getCryptStr {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"gameId"] = [ZCFunDataFormat GetQPGameID];
    params[@"platformId"] = YZYPlatformID;
    params[@"sdkVersion"] = YZYSDKVERSION;
    params[@"deviceName"] = [ZCFunDataFormat getCurrentDeviceModel];
    params[@"osType"] = @"2";
    params[@"systemVersion"] = [ZCFunDataFormat getDeviceSystemVersion];
    params[@"serviceId"] = self.roleInfo.service_id;
    params[@"serviceName"] = self.roleInfo.service_name;
    params[@"userId"] = self.roleInfo.super_user_id;
    params[@"chanelUserId"] = self.roleInfo.user_id;
    params[@"roleIdPublish"] = self.roleInfo.super_role_id;//传平台角色id
    params[@"roleId"] = self.roleInfo.role_id;//传研发角色id
    params[@"roleName"] = self.roleInfo.role_name;
    params[@"token"] = [YZYSaccountStore sharedInstance].getAccessToken;
    
    NSLog(@"yzysdk - H5SocialView - doEncryptStr - %@", params);
    NSError *paramsError;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&paramsError];
    NSString *paramsStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *doEncryptStr = [ZCNetworkManager doEncryptStr:paramsStr];
    return doEncryptStr;
}

- (void)closeH5
{
    NSLog(@"yzysdk - H5SocialView - closeH5");
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.coverView removeFromSuperview];
        [self.wkWebView removeFromSuperview];
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(closeH5SocialView)]) {
            [self.delegate closeH5SocialView];
        };
    });
}

- (void)callJS:(NSDictionary *)content {
    NSLog(@"yzysdk - H5SocialView - content - %@", content);
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:content options:NSJSONWritingPrettyPrinted error:&error];
    NSString *value = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *js = [[NSString alloc] initWithFormat:@"CallbackFromIOS('%@')", [self base64encode:value]];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.wkWebView evaluateJavaScript:js completionHandler:^(id Result, NSError * error) {
        }];
    });
}

- (NSString*)base64encode:(NSString*)str {
    NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
    return [data base64EncodedStringWithOptions:0];
}

- (NSString*)base64Decode:(NSString*)str {
    NSData* data = [[NSData alloc] initWithBase64EncodedString:str options:0];
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

- (void)showH5SocialView {
    NSLog(@"yzysdk - H5SocialView - showH5SocialView");
    [[YZYSaccountStore sharedInstance] getCurrentWindowWithCompletion:^(UIWindow *window) {
        if (window) {
//            UIButton *coverView = [[UIButton alloc] init];
//            coverView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3f];
//            [window addSubview:coverView];
//            [coverView mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.edges.equalTo(window);
//            }];
//            self.coverView = coverView;
//
//            UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
//            UIVisualEffectView *visualView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
//            visualView.alpha = 0.0;
//            [coverView addSubview:visualView];
//            [visualView mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.edges.equalTo(coverView);
//            }];
//            [window addSubview:self];
//            [self mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.edges.equalTo(coverView);
//            }];
//
//            UIImageView *backbg = [[UIImageView alloc] init];
//            backbg.userInteractionEnabled = YES;
//            backbg.backgroundColor = [UIColor whiteColor];
//            backbg.layer.masksToBounds = YES;
//            backbg.layer.cornerRadius = 4;
//            [self addSubview:backbg];
//            [backbg mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.edges.equalTo(self);
//            }];
            
            [window addSubview:self.wkWebView];
            [self.wkWebView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(window);
            }];
            
            [self loadUrl];
        }
    }];
}

// 编码
- (NSString *)URLEncodedString:(NSString *)str{
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)str,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    return encodedString;
}
// 解码
- (NSString *)URLDecodedString:(NSString *)str{
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    
    return decodedString;
}

- (NSDictionary *)convertDictionary:(NSDictionary *)dictionary {
    NSMutableDictionary *temDict = [NSMutableDictionary dictionary];
    for (NSString *key in dictionary.allKeys) {
        NSString *value = dictionary[key];
        if ([value isKindOfClass:[NSString class]]) {
            [temDict setObject:value forKey:key];
        } else if ([value isKindOfClass:[NSNumber class]]) {
            NSNumber *valueNumber = (NSNumber *)value;
            [temDict setObject:valueNumber.stringValue forKey:key];
        } else if ([value isKindOfClass:[NSDictionary class]]) {
            NSDictionary *valueDictioanry = (NSDictionary *)value;
            [temDict setObject:[self convertDictionary:valueDictioanry] forKey:key];
        }
    }
    return temDict;
}

@end
